<template>
  <div class="StaticExtensionDetail">
    <div class="title">
      <h3>推广详情</h3>
    </div>
    <div class="key-search">
      <el-form ref="form" :model="BindForm" label-width="80px" label-position="left">
        <el-form-item prop="schemeId" label="推广方案:">
          <el-col :span="24">
            <ExtensionSchemeSelect v-model="BindForm.schemeId" />
          </el-col>
        </el-form-item>
        <el-form-item prop="agentId" label="推广员:">
          <el-col :span="24">
            <ExtensionUserSelect v-model="BindForm.agentId" />
          </el-col>
        </el-form-item>
        <el-form-item prop="allCity" label="门店:">
          <city-select ref="citySelect" v-model="BindForm.address" style="margin-left: 0" @change="changedAddress" />
          <store-select ref="storeSelect" v-model="BindForm.store" field="id" />
        </el-form-item>
        <el-form-item prop="time" label="查询时段:">
          <el-col :span="24">
            <el-date-picker
              v-model="BindForm.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="center"
              clearable
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
            />
            <el-button plain style="margin-left:10px" @click="setWeek">最近一周</el-button>
            <el-button plain @click="setMonth">最近一月</el-button>
            <el-button plain @click="setYear">最近一年</el-button>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">筛选</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="Infos && BindTable && BindTable.length > 0" class="key-type">
      <div />
      <el-button
        type="primary"
        @click="exportData"
      >导出数据</el-button>
    </div>
    <el-row v-if="Infos" class="cus-header-content" :gutter="10">
      <el-col :span="3">
        <div class="cus-header-item">
          <div class="cus-header-item-title">累计订单(/个)</div>
          <div class="cus-header-item-count">{{ Infos.orderCount != undefined ? Infos.orderCount : 0 }}</div>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="cus-header-item">
          <div class="cus-header-item-title">累计销售额</div>
          <div class="cus-header-item-count">￥{{ Infos.orderPriceCount.toFixed(2) }}</div>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="cus-header-item">
          <div class="cus-header-item-title">累计客户(/个)</div>
          <div class="cus-header-item-count">{{ Infos.customerCount != undefined ? Infos.customerCount : 0 }}</div>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="cus-header-item">
          <div class="cus-header-item-title">推广客户(/个)</div>
          <div class="cus-header-item-count">{{ Infos.promoterCount != undefined ? Infos.promoterCount : 0 }}</div>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="cus-header-item">
          <div class="cus-header-item-title">访问用户(/个)</div>
          <div class="cus-header-item-count">{{ Infos.visitorCount != undefined ? Infos.visitorCount : 0 }}</div>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="cus-header-item">
          <div class="cus-header-item-title">累计佣金</div>
          <div class="cus-header-item-count">￥{{ Infos.commissionCount.toFixed(2) }}</div>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="cus-header-item">
          <div class="cus-header-item-title">已结算</div>
          <div class="cus-header-item-count">￥{{ Infos.isSettlementPrice.toFixed(2) }}</div>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="cus-header-item">
          <div class="cus-header-item-title">待结算</div>
          <div class="cus-header-item-count">￥{{ Infos.unSettlementPrice.toFixed(2) }}</div>
        </div>
      </el-col>
    </el-row>
    <div class="ele-table">
      <el-table :data="BindTable" border max-height="600" :empty-text="loading ? '数据加载中' : (isSearch ? '未找到相关的统计数据' : '暂无统计数据')">
        <el-table-column
          label="日期"
          prop="promoterDate"
          align="center"
          :resizable="false"
          fixed="left"
          min-width="120"
        />
        <el-table-column
          label="累计订单(/个)"
          prop="orderCount"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.orderCount != undefined ? scope.row.orderCount : 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="累计销售额"
          prop="orderPriceCount"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span>￥{{ scope.row.orderPriceCount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="累计客户(/个)"
          prop="customerCount"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.customerCount != undefined ? scope.row.customerCount : 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="推广客户(/个)"
          prop="promoterCount"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.promoterCount != undefined ? scope.row.promoterCount : 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="访问用户(/个)"
          prop="visitorCount"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.visitorCount != undefined ? scope.row.visitorCount : 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="累计佣金"
          prop="commissionCount"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span>￥{{ scope.row.commissionCount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="已结算"
          prop="isSettlementPrice"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span>￥{{ scope.row.isSettlementPrice.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="待结算"
          prop="unSettlementPrice"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span>￥{{ scope.row.unSettlementPrice.toFixed(2) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <div />
      <el-pagination
        background
        :page-sizes="[10, 20, 30, 50, 100]"
        :page-size="limit"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="pageSizeChange"
        @current-change="currentPageChange"
      />
    </div>
  </div>
</template>

<script>
import {
  ExtensionManagementInfo,
  ExtensionStaticDetail,
  ExtensionExportData
} from '@/api/customAPI/shop/ExtensionManagement'
import ExtensionSchemeSelect from '../../../components/ExtensionSchemeSelect/index'
import ExtensionUserSelect from '../../../components/ExtensionUserSelect/index'
import CitySelect from '../../../components/CitySelect/index'
import StoreSelect from '../../../components/StoreSelect/index'
import { Loading } from 'element-ui'
export default {
  name: 'StaticExtensionDetail',
  components: { StoreSelect, CitySelect, ExtensionUserSelect, ExtensionSchemeSelect },
  data() {
    return {
      page: 1,
      limit: 10,
      total: 0,
      loading: false,
      isSearch: false,
      Infos: null,
      BindForm: {
        allCity: true,
        schemeId: null,
        agentId: null,
        store: null,
        time: null,
        address: {
          province: null,
          city: null,
          village: null
        }
      },
      BindTable: []
    }
  },
  computed: {
    /* 请求头部信息*/
    headers() {
      return {
        'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'
      }
    }
  },
  created() {
    const vm = this
    vm.loadTableData()
  },
  methods: {
    changedAddress() {
      const vm = this
      if (vm.BindForm.address.province || vm.BindForm.address.city || vm.BindForm.address.village) {
        vm.BindForm.allCity = false
      } else {
        vm.BindForm.allCity = true
      }

      const provinceId = vm.BindForm.address.province ? vm.BindForm.address.province.code : null
      const cityId = vm.BindForm.address.city ? vm.BindForm.address.city.code : null
      const villageId = vm.BindForm.address.village ? vm.BindForm.address.village.code : null

      vm.$refs.storeSelect.refresh(provinceId, cityId, villageId)
    },
    setWeek() {
      const vm = this
      const start = new Date()
      const end = new Date()
      start.setHours(0)
      start.setMinutes(0)
      start.setSeconds(0)
      end.setHours(23)
      end.setMinutes(59)
      end.setSeconds(59)
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
      vm.BindForm.time = [
        vm.$XEUtils.toDateString(start, 'yyyy-MM-dd'),
        vm.$XEUtils.toDateString(end, 'yyyy-MM-dd')
      ]
    },
    setMonth() {
      const vm = this
      const start = new Date()
      const end = new Date()
      start.setHours(0)
      start.setMinutes(0)
      start.setSeconds(0)
      end.setHours(23)
      end.setMinutes(59)
      end.setSeconds(59)
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
      vm.BindForm.time = [
        vm.$XEUtils.toDateString(start, 'yyyy-MM-dd'),
        vm.$XEUtils.toDateString(end, 'yyyy-MM-dd')
      ]
    },
    setYear() {
      const vm = this
      const start = new Date()
      const end = new Date()
      start.setHours(0)
      start.setMinutes(0)
      start.setSeconds(0)
      end.setHours(23)
      end.setMinutes(59)
      end.setSeconds(59)
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
      vm.BindForm.time = [
        vm.$XEUtils.toDateString(start, 'yyyy-MM-dd'),
        vm.$XEUtils.toDateString(end, 'yyyy-MM-dd')
      ]
    },
    loadExtensionManagementInfo(data) {
      const vm = this
      ExtensionManagementInfo(data)
        .then(result => {
          vm.Infos = result.data.data
        })
        .catch(res => {
          console.log(res)
          if (res && res.data && res.data.errno !== 0) {
            vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
          }
        })
    },
    resetForm() {
      const vm = this
      vm.$refs.citySelect.resetFields()
      vm.$refs.form.resetFields()
      vm.reloadTableData()
    },
    search() {
      const vm = this
      vm.$refs.form.validate((valid) => {
        if (valid) {
          vm.reloadTableData()
        }
      })
    },
    pageSizeChange(pageSize) {
      const vm = this

      vm.limit = pageSize

      vm.reloadTableData()
    },
    currentPageChange(page) {
      const vm = this

      vm.page = page

      vm.loadTableData()
    },
    handleSelectionChange(val) {
      this.selectedList = val
    },
    selectable(row, index) {
      if (row['state'] === 0 || row['state'] === 1) {
        return true
      }
      return false
    },
    reloadTableData() {
      const vm = this

      vm.page = 1
      vm.total = 0
      vm.BindTable = []
      vm.loadTableData()
    },
    exportData() {
      const vm = this

      vm.isSearch = false

      const data = this.$XEUtils.clone(this.BindForm, true)

      delete data.allCity

      if (data.schemeId) {
        vm.isSearch = true
      } else {
        delete data.schemeId
      }

      if (data.agentId) {
        vm.isSearch = true
      } else {
        delete data.agentId
      }

      if (data.address.province) {
        data['provinceId'] = data.address.province.code
        vm.isSearch = true
      }
      if (data.address.city) {
        data['cityId'] = data.address.city.code
        vm.isSearch = true
      }
      if (data.address.village) {
        data['villageId'] = data.address.village.code
        vm.isSearch = true
      }

      if (data.store) {
        data['storeId'] = data.store
        vm.isSearch = true
      }

      if (data.time && data.time.length === 2) {
        data['startDate'] = data.time[0]
        data['endDate'] = data.time[1]
        vm.isSearch = true
      }

      delete data.address
      delete data.time
      delete data.store

      data['shopId'] = localStorage.getItem('shopId')

      const loadingInstance = Loading.service()

      ExtensionExportData(data).then(res => {
        loadingInstance.close()
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        if (window.navigator.msSaveBlob) { // IE以及IE内核的浏览器使用
          try {
            window.navigator.msSaveBlob(blob, '推广统计报表-' + vm.$XEUtils.toDateString(new Date(), 'yyyy-MM-dd HHmmss-SSS') + '.xls')
            // window.navigator.msSaveOrOpenBlob(response, fileNm);    //fileNm是文件的名字
          } catch (e) {
            console.log(e)
          }
        } else {
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', '推广统计报表-' + vm.$XEUtils.toDateString(new Date(), 'yyyy-MM-dd HHmmss-SSS') + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
        // 配置导出excel的文件名
        /* const fileName = '推广统计报表-' + vm.$XEUtils.toDateString(new Date(), 'yyyy-MM-dd HHmmss-SSS') + '.xlsx'
        vm.downFile(res, fileName)*/
      }).catch(res => {
        loadingInstance.close()
        if (res && res.data && res.data.errno !== 0) {
          vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    },
    /* downFile(data, fileName) {
      const vm = this
      if (!data) {
        return false
      }
      vm.$message({
        type: 'success',
        message: '导出完成，请您注意浏览器的下载管理器！'
      })
      // 下面就是DOM操作 1.添加一个a标签 2.给a标签添加了属性 3.给他添加了点击事件(点击后移除)
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      link.remove()
    },*/
    loadTableData() {
      const vm = this

      vm.isSearch = false

      const data = this.$XEUtils.clone(this.BindForm, true)

      delete data.allCity

      if (data.schemeId) {
        vm.isSearch = true
      } else {
        delete data.schemeId
      }

      if (data.agentId) {
        vm.isSearch = true
      } else {
        delete data.agentId
      }

      if (data.address.province) {
        data['provinceId'] = data.address.province.code
        vm.isSearch = true
      }
      if (data.address.city) {
        data['cityId'] = data.address.city.code
        vm.isSearch = true
      }
      if (data.address.village) {
        data['villageId'] = data.address.village.code
        vm.isSearch = true
      }

      if (data.store) {
        data['storeId'] = data.store
        vm.isSearch = true
      }

      if (data.time && data.time.length === 2) {
        data['startDate'] = data.time[0]
        data['endDate'] = data.time[1]
        vm.isSearch = true
      }

      delete data.address
      delete data.time
      delete data.store

      data['shopId'] = localStorage.getItem('shopId')

      if (vm.page == 1) {
        vm.Infos = null
        vm.loadExtensionManagementInfo(data)
      }

      vm.loading = true

      ExtensionStaticDetail({
        page: vm.page,
        limit: vm.limit,
        ...data
      }).then(res => {
        console.log(res.data.data.data)
        vm.loading = false
        vm.total = res.data.data.total
        vm.BindTable = res.data.data.data ? res.data.data.data : []
      }).catch(res => {
        vm.loading = false
        if (res && res.data && res.data.errno !== 0) {
          vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.StaticExtensionDetail{
  padding: 30px;

  .cus-header-content {
    padding: 10px 5px;
    border-radius: 5px;
    background: #f3f3f3;
    margin-bottom: 40px;

    .cus-header-item {
      padding: 12px;
      background: #ffffff;
      border-radius: 5px;
      display: flex;
      flex-direction: column;

      &-title {
        font-weight: bold;
        font-size: 14px;
      }

      &-count {
        font-size: 14px;
        margin-top: 10px;
      }
    }

  }

  .ibox {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 10px;
    .ibox-info {
     .ibox-title {
      font-size: 18px;
     }
      .ibox-desc {
        margin-top: 10px;
        font-size: 24px;
        font-weight: bold;
      }
    }
    .ibox-icon {
      font-size: 24px;
    }
  }

  .ibox:active {
    background: #f1f1f1;
  }

  .key-search {
    margin-top: 30px;
    padding: 20px 30px;
    padding-bottom: 0px;
    margin-bottom: 30px;
    border: 1px solid #eeeeee;
    .cus-input {
      max-width: 400px;
    }
  }

  .key-type {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30px;
  }
  .ele-table,
  .pagination {
    margin-bottom: 30px;
  }
  .pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

}
</style>
